/* $RCSFile: MasterPageManager.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Design/MasterPageManager.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Globalization;

using AddonNice.Diagnostics;

using Path2     =   AddonNice.Settings.Path;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;
using Key2      =   AddonNice.Settings.Cache.Key;

namespace AddonNice.Design
{
    /// <summary>
    /// The MasterPageManager class encapsulates all data logic necessary to
    /// use differents Layouts across the entire portal.
    /// Manages the Load and Save of the Layouts.
    /// Encapsulates a Layout object that contains all the settings
    /// of the current Layout.
    /// </summary>
	public class MasterPageManager
    {
        const string strMasterPage                  =   "/MasterPages";
        string _portalPath							=	string.Empty;


        /// <summary>
        /// portalPath is the portal name, ex for Addonnice portal it is '_addonnice'
        /// </summary>
        /// <param name="portalPath"></param>
        public MasterPageManager(string portalPath)
        {
            _portalPath = portalPath;
        }

		public void ClearCacheList()
		{
			//Clear cache
			lock (typeof(MasterPageManager))
			{
                Cache2.Remove(Key2.MasterPageList(GetPath()));
            }
		}


		/// <summary>
		/// The virtual path of the default MasterPage dir (Web side)
        /// Default value : '~/MasterPages'
        /// </summary>
        public static string GetGlobalWebPath()
        {
            return Path2.WebPathCombine(Path2.ApplicationRoot, strMasterPage);
        }


        /// <summary>
        /// The virtual path of the current portal Master Pages dir (Web side)
        /// Default value : '~/Portal+'/MasterPages'
        /// </summary>
        public string GetPortalWebPath()
        {
            return Path2.WebPathCombine(Path2.ApplicationRoot, _portalPath,strMasterPage);
        }

		/// <summary>
		/// The physical path of the Global site Master Pages dir (Physical path) used to load masterfiles names
        /// correspond to virtual folder GlobalWebPath
		/// </summary>
		public static string GetPath()
        {
            return HttpContext.Current.Server.MapPath(GetGlobalWebPath());
        }

        /// <summary>
        /// The physical path of the current portal Master Pages dir (Physical path) used to load specific MasterPages
        /// correspond to virtual folder PortalWebPath
        /// </summary>
        public string GetPortalPath()
        {
            return HttpContext.Current.Server.MapPath(GetPortalWebPath());
        }

		/// <summary>
		/// Read the Path dir and returns
		/// an ArrayList with all the Layouts found, public and privates
		/// </summary>
		/// <returns></returns>
        public ArrayList GetMasterPages()
		{
            ArrayList layoutList            = (ArrayList)GetPublicMasterPages().Clone();
            ArrayList layoutListPrivate     = GetPrivateMasterPages();

			layoutList.AddRange(layoutListPrivate);

			return layoutList;
		}

		/// <summary>
		/// Read the Path dir and returns an ArrayList with all the Layouts found.
		/// Static because the list is Always the same.
		/// </summary>
		/// <returns></returns>
        public static ArrayList GetPublicMasterPages()
		{
			ArrayList baseLayoutList;
            string webPath          =   GetGlobalWebPath();
            string wPath            =   GetPath();
            if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPublicMasterPages Path: {0}", wPath),MasterPageTraceSwitch.Sw.Info);


			if ( !Cache2.Exists(Key2.MasterPageList(wPath)) )
			{
				// initialize array
				baseLayoutList      =   new ArrayList();
				string[] layouts;

				// Try to read directories from public Layout path
				if ( Directory.Exists(wPath) )
				{
					layouts         =   Directory.GetFiles(wPath,"*.master",SearchOption.TopDirectoryOnly);
				}
				else
				{
					layouts         =   new string[0];
				}

				for (int i = 0; i < layouts.Length; i++)
				{
                    string nm   =   layouts[i];
                    string lnm  =   nm.ToLower();
                    if ( lnm.IndexOf("help") != -1 || //Ignore Help master page
                        lnm.IndexOf("error") != -1 )  // Ignore Error master help
                        continue;
                    MasterListItem t =  new MasterListItem(System.IO.Path.GetFileNameWithoutExtension(nm),webPath,ItemOrigin.Public);
					baseLayoutList.Add(t);
                    if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPublicMasterPages adding : {0}", t.Name),MasterPageTraceSwitch.Sw.Info);
                }
				Cache2.InsertLong(Key2.MasterPageList(wPath), baseLayoutList, new CacheDependency(wPath));
			}
			else
			{
				baseLayoutList      =   (ArrayList) Cache2.Get(Key2.MasterPageList(wPath));
			}
            if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPublicMasterPages Count : {0}", baseLayoutList.Count),MasterPageTraceSwitch.Sw.Info);
            return baseLayoutList;
		}
  
		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
        public ArrayList GetPrivateMasterPages()
		{
			ArrayList privateLayoutList;
            string webPath          =   GetPortalWebPath();
            string wPath            =   GetPortalPath();
            if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPrivateMasterPages PortalLayoutPath: {0}", wPath),MasterPageTraceSwitch.Sw.Info);

			if ( !Cache2.Exists(Key2.MasterPageList(wPath)) )
			{

				privateLayoutList   =   new ArrayList();
				string[] layouts;

				// Try to read directories from private theme path
				if (Directory.Exists(wPath))
				{
                    layouts         =   Directory.GetFiles(wPath, "*.master", SearchOption.TopDirectoryOnly);
                }

				else
				{
					layouts         =   new string[0];
				}

				for (int i = 0; i <= layouts.GetUpperBound(0); i++)
				{
                    string nm   =   layouts[i];
                    string lnm  =   nm.ToLower();
                    if ( lnm.IndexOf("help") != -1 || //Ignore Help master page
                        lnm.IndexOf("error") != -1 )  // Ignore Error master help
                        continue;
                    MasterListItem t =  new MasterListItem(System.IO.Path.GetFileNameWithoutExtension(nm),webPath,ItemOrigin.Portal);
                    privateLayoutList.Add(t);
                    if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPrivateMasterPages adding : {0}", t.Name),MasterPageTraceSwitch.Sw.Info);
                }
				Cache2.InsertLong(Key2.MasterPageList(wPath), privateLayoutList, new CacheDependency(wPath));
			}
			else
			{
				privateLayoutList   =   (ArrayList) Cache2.Get(Key2.MasterPageList(wPath));
			}
            if ( MasterPageTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MasterPageManager GetPrivateMasterPages Count : {0}", privateLayoutList.Count),MasterPageTraceSwitch.Sw.Info);
            return privateLayoutList;
		}
	}
}